
package com.example.android.fragments;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * 文章碎片
 */
public class ArticleFragment extends Fragment {

	// key
	final static String ARG_POSITION = "position";
	// 当前索引value
	int mCurrentPosition = -1;

	// 加载布局
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		// If activity recreated (such as from screen rotate), restore
		// the previous article selection set by onSaveInstanceState().
		// This is primarily necessary when in the two-pane layout.
		if (savedInstanceState != null) {
			mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
			System.out.println("mCurrentPosition"
					+ savedInstanceState.getInt(ARG_POSITION));
		}
		// Inflate the layout for this fragment
		return inflater.inflate(R.layout.article_view, container, false);

	}

	//
	@Override
	public void onStart() {
		super.onStart();

		// During startup, check if there are arguments passed to the fragment.
		// onStart is a good place to do this because the layout has already
		// been
		// applied to the fragment at this point so we can safely call the
		// method
		// below that sets the article text.
		// 接受从activity传进来的参数
		Bundle args = getArguments();
		if (args != null) {
			// Set article based on argument passed in

			updateArticleView(args.getInt(ARG_POSITION));

		}
		// 接收savedInstanceState里面的参数
		else if (mCurrentPosition != -1) {
			// Set article based on saved instance state defined during
			// onCreateView
			updateArticleView(mCurrentPosition);
		}
	}

	// 给text设值
	public void updateArticleView(int position) {
		TextView article = (TextView) getActivity().findViewById(R.id.article);
		article.setText(Ipsum.Articles[position]);
		mCurrentPosition = position;
	}

	// 存贮内容
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		// Save the current article selection in case we need to recreate the
		// fragment
		outState.putInt(ARG_POSITION, mCurrentPosition);
	}
}